import React, { useState, useEffect, useRef } from 'react';
import { Table, Spin, message, Input, Button, Modal, Select, Form, InputNumber } from 'antd';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { LeftOutlined, RightOutlined, EditOutlined } from '@ant-design/icons';

// 模型映射组件样式
const modelMappingStyles = `
  .model-mapping-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
    background: #fff;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  @media (max-width: 576px) {
    .model-mapping-container {
      margin: 0;
      border-radius: 0;
    }
  }
`;

// 模型映射组件
const ModelMapping = () => {
  const [loading, setLoading] = useState(false);
  const [mappingList, setMappingList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [isMobile, setIsMobile] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);
  const [featureDetailsMap, setFeatureDetailsMap] = useState({});
  const [modelDetailsMap, setModelDetailsMap] = useState({});
  
  // 批量修改相关状态
  const [batchEditVisible, setBatchEditVisible] = useState(false);
  const [batchEditLoading, setBatchEditLoading] = useState(false);
  const [batchEditForm] = Form.useForm();
  const [allFeatures, setAllFeatures] = useState([]);
  const [batchUpdating, setBatchUpdating] = useState(false);
  const [allMappingList, setAllMappingList] = useState([]);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取模型映射列表
  useEffect(() => {
    fetchModelMappings();
  }, [currentPage, pageSize]);
  
  // 初始加载
  useEffect(() => {
    console.log('ModelMapping组件已加载');
  }, []);

  // 获取模型映射数据
  const fetchModelMappings = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/feature_model_mapping`, {
        params: {
          skip: (currentPage - 1) * pageSize, // skip 表示要跳过的记录数
          limit: pageSize
        }
      });
      
      if (response.data && response.data.code === 200) {
        console.log('模型映射列表:', response.data.data);
        const items = response.data.data.items || [];
        setMappingList(items);
        
        // 更新分页信息
        setPagination({
          current: currentPage,
          pageSize: pageSize,
          total: response.data.data.total || 0
        });
        
        // 获取每个映射相关的特征和模型详情
        fetchRelatedDetails(items);
        
        if (items.length === 0 && response.data.data.total > 0) {
          message.info('当前页没有数据');
        }
      } else {
        message.error('获取模型映射列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取模型映射列表错误:', error);
      message.error('获取模型映射列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取关联的特征和模型详情
  const fetchRelatedDetails = async (mappings) => {
    // 获取唯一的特征和模型ID列表
    const featureIds = [...new Set(mappings.map(item => item.feature_id))];
    const modelIds = [...new Set(mappings.map(item => item.model_id))];
    
    // 创建临时存储对象
    const featureDetails = { ...featureDetailsMap };
    const modelDetails = { ...modelDetailsMap };
    
    // 获取缺失的特征详情
    const missingFeatureIds = featureIds.filter(id => !featureDetails[id]);
    for (const featureId of missingFeatureIds) {
      try {
        const response = await axios.get(`${API_BASE_URL}/api/feature_definition/${featureId}`);
        if (response.data && response.data.code === 200) {
          console.log(`获取特征 ${featureId} 详情:`, response.data.data);
          featureDetails[featureId] = response.data.data;
        }
      } catch (error) {
        console.error(`获取特征 ${featureId} 详情失败:`, error);
      }
    }
    
    // 获取缺失的模型详情
    const missingModelIds = modelIds.filter(id => !modelDetails[id]);
    for (const modelId of missingModelIds) {
      try {
        const response = await axios.get(`${API_BASE_URL}/api/recommendation_model/${modelId}`);
        if (response.data && response.data.code === 200) {
          modelDetails[modelId] = response.data.data;
        }
      } catch (error) {
        console.error(`获取模型 ${modelId} 详情失败:`, error);
      }
    }
    
    setFeatureDetailsMap(featureDetails);
    setModelDetailsMap(modelDetails);
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        setCurrentPage(value);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(currentPage + 1);
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    
    try {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    } catch (e) {
      return dateString;
    }
  };

  // 获取表格列定义
  const getColumns = () => {
    const baseColumns = [
      {
        title: '特征编码',
        dataIndex: 'feature_id',
        key: 'feature_code',
        align: 'center',
        width: 120,
        render: (featureId) => {
          const feature = featureDetailsMap[featureId] || {};
          return <span>{feature.feature_code || feature.code || '-'}</span>;
        }
      },
      {
        title: '特征名称',
        dataIndex: 'feature_id',
        key: 'feature_name',
        align: 'left',
        width: 150,
        render: (featureId) => {
          const feature = featureDetailsMap[featureId] || {};
          return <span>{feature.feature_name || feature.name || '-'}</span>;
        }
      },
      {
        title: '模型编码',
        dataIndex: 'model_id',
        key: 'model_code',
        align: 'center',
        width: 120,
        render: (modelId) => {
          const model = modelDetailsMap[modelId] || {};
          return <span>{model.code || '-'}</span>;
        }
      },
      {
        title: '模型名称',
        dataIndex: 'model_id',
        key: 'model_name',
        align: 'left',
        width: 150,
        render: (modelId) => {
          const model = modelDetailsMap[modelId] || {};
          return <span>{model.name || '-'}</span>;
        }
      },
      {
        title: '映射权重',
        dataIndex: 'weight',
        key: 'mapping_weight',
        align: 'center',
        width: 100,
        render: (value) => <span>{value || '-'}</span>
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        width: 180,
        render: (text) => <span>{formatDate(text)}</span>
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        key: 'update_time',
        align: 'center',
        width: 180,
        render: (text) => <span>{formatDate(text)}</span>
      }
    ];
    
    // 移动端只显示核心列
    if (isMobile) {
      return baseColumns.filter(column => 
        ['feature_code', 'feature_name', 'model_code', 'weight'].includes(column.dataIndex) ||
        (column.key === 'feature_code' || column.key === 'feature_name' || 
         column.key === 'model_code' || column.key === 'mapping_weight')
      );
    }
    
    return baseColumns;
  };

  // 获取行样式
  const getRowClassName = () => {
    if (mappingList.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 自定义分页样式
  const customPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };

  // 获取所有特征列表
  const fetchAllFeatures = async () => {
    try {
      // 首先从所有映射中提取唯一的特征ID
      const allMappings = await fetchAllMappings();
      const mappingFeatureIds = [...new Set(allMappings.map(item => item.feature_id))];
      console.log('从映射中提取的特征ID:', mappingFeatureIds);
      
      // 获取特征定义列表
      const response = await axios.get(`${API_BASE_URL}/api/feature_definition`);
      if (response.data && response.data.code === 200) {
        console.log('API返回的特征列表:', response.data.data);
        let featureList = response.data.data.items || [];
        
        // 检查映射中的特征ID是否都包含在特征列表中
        const featureListIds = featureList.map(f => f.id);
        const missingFeatureIds = mappingFeatureIds.filter(id => !featureListIds.includes(id));
        
        // 如果有缺失的特征ID，分别获取其详情并添加到列表中
        if (missingFeatureIds.length > 0) {
          console.log('缺失的特征ID:', missingFeatureIds);
          
          const featureDetails = { ...featureDetailsMap };
          
          for (const featureId of missingFeatureIds) {
            try {
              const featureResponse = await axios.get(`${API_BASE_URL}/api/feature_definition/${featureId}`);
              if (featureResponse.data && featureResponse.data.code === 200) {
                featureDetails[featureId] = featureResponse.data.data;
                
                // 添加到特征列表
                featureList.push(featureResponse.data.data);
              }
            } catch (error) {
              console.error(`获取特征 ${featureId} 详情失败:`, error);
            }
          }
          
          // 更新特征详情映射
          setFeatureDetailsMap(featureDetails);
        }
        
        // 设置完整的特征列表
        console.log('合并后的特征列表:', featureList);
        setAllFeatures(featureList);
      }
    } catch (error) {
      console.error('获取特征列表错误:', error);
    }
  };
  
  // 获取所有映射数据（不分页）
  const fetchAllMappings = async () => {
    setBatchUpdating(true);
    try {
      // 首先获取总记录数
      const countResponse = await axios.get(`${API_BASE_URL}/api/feature_model_mapping`, {
        params: {
          limit: 1
        }
      });
      
      if (countResponse.data && countResponse.data.code === 200) {
        const totalCount = countResponse.data.data.total || 0;
        console.log('映射总记录数:', totalCount);
        
        // 获取所有数据
        const response = await axios.get(`${API_BASE_URL}/api/feature_model_mapping`, {
          params: {
            skip: 0,
            limit: totalCount
          }
        });
        
        if (response.data && response.data.code === 200) {
          const items = response.data.data.items || [];
          setAllMappingList(items);
          return items;
        }
      }
      return [];
    } catch (error) {
      console.error('获取所有映射数据错误:', error);
      message.error('获取所有映射数据失败: ' + (error.message || '网络错误'));
      return [];
    } finally {
      setBatchUpdating(false);
    }
  };

  // 显示批量修改窗口
  const showBatchEditModal = async () => {
    setBatchEditVisible(true);
    batchEditForm.resetFields();
    // 获取所有特征列表供用户选择
    fetchAllFeatures();
    // 获取所有映射数据
    await fetchAllMappings();
  };

  // 关闭批量修改窗口
  const handleBatchEditCancel = () => {
    setBatchEditVisible(false);
  };

  // 批量修改提交
  const handleBatchEditSubmit = async () => {
    try {
      const values = await batchEditForm.validateFields();
      console.log('批量修改值:', values);
      
      const { feature_id, mapping_weight } = values;
      
      setBatchEditLoading(true);
      setBatchUpdating(true);
      
      if (feature_id) {
        // 选择了特定特征，只更新该特征的映射
        await batchUpdateFeatureMappings(feature_id, mapping_weight);
      } else {
        // 未选择特征，更新所有映射
        await batchUpdateAllMappings(mapping_weight);
      }
      
      message.success('批量修改成功');
      setBatchEditVisible(false);
      fetchModelMappings(); // 重新加载数据
    } catch (error) {
      console.error('表单验证或提交错误:', error);
      message.error('批量修改失败: ' + (error.message || '未知错误'));
    } finally {
      setBatchEditLoading(false);
      setBatchUpdating(false);
    }
  };

  // 批量更新特定特征的映射权重
  const batchUpdateFeatureMappings = async (featureId, weight) => {
    // 找出所有匹配该特征ID的映射
    const filteredMappings = allMappingList.filter(mapping => 
      mapping.feature_id && mapping.feature_id.toString() === featureId.toString()
    );
    
    if (filteredMappings.length === 0) {
      message.info('未找到匹配的特征映射');
      return;
    }
    
    let successCount = 0;
    let errorCount = 0;
    
    for (const mapping of filteredMappings) {
      try {
        const response = await axios.put(`${API_BASE_URL}/api/feature_model_mapping/${mapping.id}`, {
          weight: weight
        });
        
        if (response.data && (response.data.code === 200 || response.data.code === 201)) {
          successCount++;
        } else {
          errorCount++;
          console.error('更新映射失败:', response.data);
        }
      } catch (error) {
        errorCount++;
        console.error('更新映射错误:', error);
      }
    }
    
    message.info(`批量更新完成，成功: ${successCount}，失败: ${errorCount}`);
  };

  // 批量更新所有映射权重
  const batchUpdateAllMappings = async (weight) => {
    let successCount = 0;
    let errorCount = 0;
    
    for (const mapping of allMappingList) {
      try {
        const response = await axios.put(`${API_BASE_URL}/api/feature_model_mapping/${mapping.id}`, {
          weight: weight
        });
        
        if (response.data && (response.data.code === 200 || response.data.code === 201)) {
          successCount++;
        } else {
          errorCount++;
          console.error('更新映射失败:', response.data);
        }
      } catch (error) {
        errorCount++;
        console.error('更新映射错误:', error);
      }
    }
    
    message.info(`批量更新完成，成功: ${successCount}，失败: ${errorCount}`);
  };

  return (
    <div className="model-mapping-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <style dangerouslySetInnerHTML={{ __html: modelMappingStyles }} />
      
      {/* 表格标题和操作区 */}
      <div className="table-header-actions">
        <div>
          {/* 已移除记录数显示 */}
        </div>
        <div>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            onClick={showBatchEditModal}
            style={{ marginLeft: 8 }}
          >
            批量修改
          </Button>
        </div>
      </div>
      
      {/* 数据表格 */}
      <Spin spinning={loading || batchUpdating}>
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            className={`data-table ${mappingList.length >= 10 || isMobile ? 'compact-table' : ''}`}
            dataSource={mappingList}
            columns={getColumns()}
            rowKey="id"
            pagination={false}
            rowClassName={getRowClassName}
            size={isMobile || mappingList.length >= 10 ? 'small' : 'middle'}
            bordered={true}
            scroll={{ x: isMobile ? 800 : 'max-content' }}
            tableLayout="auto"
            locale={{ emptyText: '暂无数据' }}
          />
        </div>
        
        {/* 自定义分页 */}
        <div style={customPaginationStyle} className="pagination-container">
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button 
              icon={<LeftOutlined />}
              onClick={goPrevPage}
              disabled={currentPage === 1}
              style={{ marginRight: '8px' }}
            />
            
            <Input
              ref={inputRef}
              style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
              value={currentPage}
              onChange={handlePageInputChange}
              onKeyPress={handlePageInputKeyPress}
            />
            
            <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
            
            <Button 
              icon={<RightOutlined />}
              onClick={goNextPage}
              disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
              style={{ marginLeft: '8px', marginRight: '8px' }}
            />
            
            <span style={{ marginLeft: '8px' }}>
              10 / 页
            </span>
          </div>
        </div>
      </Spin>

      {/* 批量修改模态框 */}
      <Modal
        title="批量修改映射权重"
        open={batchEditVisible}
        onCancel={handleBatchEditCancel}
        footer={[
          <Button key="cancel" onClick={handleBatchEditCancel}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={batchEditLoading}
            onClick={handleBatchEditSubmit}
          >
            确认修改
          </Button>
        ]}
        maskClosable={false}
        destroyOnClose={true}
        width={500}
      >
        <Form
          form={batchEditForm}
          layout="vertical"
          initialValues={{ mapping_weight: 1.0 }}
        >
          <Form.Item
            label="特征名称(可选)"
            name="feature_id"
            extra="不选择特征将修改系统中所有映射的权重"
          >
            <Select
              placeholder="选择要批量修改的特征(可选)"
              allowClear
              showSearch
              optionFilterProp="label"
              filterOption={(input, option) => 
                option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              options={allFeatures.map(feature => ({
                value: feature.id,
                label: `${feature.feature_name || feature.name || '未命名特征'} (ID: ${feature.id})`
              }))}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item
            label="映射权重"
            name="mapping_weight"
            rules={[
              { required: true, message: '请输入映射权重' },
              { type: 'number', min: 0, max: 1, message: '映射权重必须在0-1之间' }
            ]}
            extra="设置特征与模型之间的映射权重，值范围0-1"
          >
            <InputNumber
              min={0}
              max={1}
              step={0.1}
              precision={2}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ModelMapping; 